﻿#if DEVELOP
using Microsoft.AspNetCore.Mvc;
using MultiAgentsShared;
using System.Text;

namespace MultiAgentsServer.Scripts.Services;

[Route("v1/chat/completions")]
[ApiController]
public class ChatTranspondService : ControllerBase
{
    private readonly HttpClient _httpClient;

    public ChatTranspondService()
    {
        _httpClient = new HttpClient
        {
            BaseAddress = new Uri("http://gpt.lhxm.link/")
        };


        string? openAiApiKey = Environment.GetEnvironmentVariable("OPENAI_KEY_DEVELOP");

        if (openAiApiKey == null) {
            Debug.LogError("OPENAI_KEY not found.");
            return;
        }

        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {openAiApiKey}");
    }

    [HttpPost]
    public async Task<IActionResult> ForwardToOpenAI()
    {
        StreamReader requestBodyStream = new(Request.Body);
        string requestBody = await requestBodyStream.ReadToEndAsync();

        StringContent requestContent = new(requestBody, Encoding.UTF8, "application/json");

        string openAiUrl = "v1/chat/completions";

        HttpRequestMessage requestMessage = new(HttpMethod.Post, openAiUrl)
        {
            Content = requestContent
        };

        HttpResponseMessage response = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead);

        if (response.IsSuccessStatusCode)
        {
            Response.StatusCode = (int)response.StatusCode;
            await response.Content.CopyToAsync(Response.Body);

            return new EmptyResult();
        }
        else
        {
            string errorContent = await response.Content.ReadAsStringAsync();
            return StatusCode((int)response.StatusCode, errorContent);
        }
    }
}
#endif